#include "praxis/core/schema_service.h"

#include <fstream>
#include <stdexcept>

namespace praxis {
struct CSchemaService::Impl {
  json root_schema_;
};

CSchemaService::CSchemaService() : impl_(std::make_unique<Impl>()) {}
CSchemaService::~CSchemaService() = default;

void CSchemaService::LoadFromFile(const std::string& filepath) {
  std::ifstream f(filepath);
  if (!f.is_open()) {
    throw std::runtime_error("Schema file not found: " + filepath);
  }
  try {
    impl_->root_schema_ = json::parse(f);
  } catch (const json::exception& e) {
    throw std::runtime_error("Failed to parse schema file: " +
                             std::string(e.what()));
  }
}

const json& CSchemaService::GetRoot() const { return impl_->root_schema_; }

const json& CSchemaService::GetSubSchema(const std::string& key) const {
  if (impl_->root_schema_.contains(key)) {
    return impl_->root_schema_.at(key);
  }
  throw std::runtime_error("Sub-schema key not found: " + key);
}
}  // namespace praxis